package com.warrantyhotel.android.service;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.util.Log;

import com.warrantyhotel.android.billing.util.Base64;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.BalanceObject;
import com.warrantyhotel.android.model.ForgotPasswordObject;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.LoginObject;
import com.warrantyhotel.android.model.PurchaseObject;
import com.warrantyhotel.android.model.RssNewsNotifyObject;
import com.warrantyhotel.android.model.TransferObject;
import com.warrantyhotel.android.model.UserInfo;
import com.warrantyhotel.android.util.DateUtis;
import com.warrantyhotel.android.util.HttpConnector;
import com.warrantyhotel.android.util.JSONParser;
import com.warrantyhotel.android.util.NewsWarrantyProcessor;

/**
 * DataUpdateService - manages connection to server, retrieves data from it,
 * parses the response and updates database with new values in background
 * thread.
 */
public class UpdateIntentService extends IntentService {

	private static final String TAG = UpdateIntentService.class.getSimpleName();

	public static final String EXTRA_STATUS_RECEIVER = "extra_receiver";
	public static final String EXTRA_REQUEST_CODE = "request_code";
	public static final String ERROR_MESSAGE = "err_msg";
	public static final String RECORDS = "records";

	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_ERROR = 2;
	public static final int STATUS_FINISHED = 3;

	private JSONParser jsonParser;
	private NewsWarrantyProcessor newsParser;
	private ContentResolver resolver;
	private static SharedPreferences prefs;

	private int queryCode;

	private final HttpConnector connector;

	public UpdateIntentService() {
		super(TAG);
		connector = HttpConnector.getInstance();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		resolver = getBaseContext().getContentResolver();
		jsonParser = new JSONParser(resolver, this);
		newsParser = new NewsWarrantyProcessor();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}

	/**
	 * This method manages sends request to a server, parses response from it
	 * and updates database with new values.
	 */
	@Override
	protected void onHandleIntent(final Intent intent) {
		// LOG.debug("Start processing request ...");

		final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		if (null != receiver)
			receiver.send(STATUS_RUNNING, null);

		queryCode = intent.getIntExtra(EXTRA_REQUEST_CODE, -1);
		final Bundle resultData = new Bundle();
		String url;
		String response = "";

		String accountId = prefs.getString(Keys._accountId, null);
		final String tokenId = prefs.getString(Keys._tokenId, null);

		// final int records;
		try {
			switch (queryCode) {
			case QueriesCodes.SELCET_COUNTRY_TABLE:
				url = "Country/List";
				response = connector.sendGETRequest(url);
				jsonParser.parseCountryJSON(new JSONObject(response));
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.SELCET_COUNTRY_TABLE);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.SELECT_STATE_TABLE:
				url = "CountryState/List";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.SELECT_STATE_TABLE);
				jsonParser.parseStateJSON(new JSONObject(response));
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.SELECT_LANGUAGE_TABLE:
				url = "Language/List";
				response = connector.sendGETRequest(url);
				jsonParser.parseLanguageJSON(new JSONObject(response));
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.SELECT_LANGUAGE_TABLE);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.SELECT_CURRENCY_TABLE:
				url = "Currency/List";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.SELECT_CURRENCY_TABLE);
				jsonParser.parseCurrencyJSON(new JSONObject(response));
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.DO_LOGIN:
				String username = intent.getStringExtra(Keys._username);
				String password = intent.getStringExtra(Keys._password);

				/* md5(login.toLowerCase() + md5 (pass)) encrypt mechanism */

				url = "SignIn/ByMail(" + DigestUtils.md5Hex((username.toLowerCase() + DigestUtils.md5Hex(password))) + ")";
				response = connector.sendGETRequest(url);
				// Log.e("DO_LOGIN", response);
				LoginObject loginObject = jsonParser.parseLoginResponse(new JSONObject(response), intent);

				boolean isLoginSuccess = loginObject.isLoginSuccess();
				long sessionTime = loginObject.getSeesionTime();
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.DO_LOGIN);
				resultData.putBoolean(Keys._isLoginSuccess, isLoginSuccess);
				resultData.putString(Keys._message, loginObject.getMessage());
				resultData.putLong(Keys._session_time, sessionTime);
				resultData.putString(Keys._firstName, loginObject.getFirstName());
				resultData.putString(Keys._lastName, loginObject.getLastName());
				if (null != receiver)
					receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.DO_REGISTRATION:
				url = "Account/Save";
				response = connector.sendPostRequest(url, intent.getStringExtra(Keys._jsregistrationObject));
				// Log.i(TAG, response);
				boolean isRegistrationSuccess = jsonParser.parseSuccessResponse(new JSONObject(response));
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.DO_REGISTRATION);
				resultData.putBoolean(Keys._isRegistrationSuccess, isRegistrationSuccess);
				resultData.putString(Keys._message, jsonParser.parseMessageResponse(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.NEARBY_STORES:
				url = "Shared/FindStoresInRange";
				JSONObject jObject = new JSONObject();
				jObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, ""));
				jObject.put(Keys.longtitude, intent.getStringExtra(Keys.longtitude));
				jObject.put(Keys.latitude, intent.getStringExtra(Keys.latitude));
				jObject.put(Keys.radius, (int) (intent.getDoubleExtra(Keys.radius, 60)));
				// Log.v("jObject", jObject.toString());
				response = connector.sendPostRequest(url, jObject.toString());
				// Log.e("sssssss", response);
				boolean clearCache = intent.getBooleanExtra(Keys.clearCacheInDb, false);
				boolean firstRun = intent.getBooleanExtra(Keys.firstRun, false);
				jsonParser.parseNearbyStyoresJSON(new JSONObject(response), clearCache);
				if (firstRun)
					resultData.putBoolean(Keys.firstRun, firstRun);
				receiver.send(STATUS_FINISHED, resultData);
				// Log.i("Shared/FindStoresInRange", response);
				break;
			case QueriesCodes.FORGOT_PASSWORG:
				url = "Shared/ResetAccountPassword";

				JSONObject jObj = new JSONObject();
				jObj.put(Keys._email, intent.getStringExtra(Keys._email));
				response = connector.sendPostRequest(url, jObj.toString());
				// Log.i(TAG, response);

				ForgotPasswordObject forgotObj = new ForgotPasswordObject();
				forgotObj.setSuccess(jsonParser.parseSuccessResponse(new JSONObject(response)));
				forgotObj.setMessage(jsonParser.parseMessageResponse(new JSONObject(response)));
				resultData.putParcelable(Keys._isPasswordForgot, forgotObj);
				receiver.send(STATUS_FINISHED, resultData);
				// Log.i("Shared/ResetAccountPassword", response);
				break;
			case QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID:
				url = "AccountUpload/ByAccountID(" + accountId + "," + tokenId + ")";
				response = connector.sendGETRequest(url);
				jsonParser.parseUploadWaJSON(new JSONObject(response));
				// Log.i("AccountUpload/ByAccountID", response);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID);
				receiver.send(STATUS_FINISHED, resultData);
				break;

			case QueriesCodes.REDEEM_CONSUME:
				String redeemCode = intent.getStringExtra(Keys._redeemCode);
				url = "Shared/ConsumeRedeem(" + redeemCode + "," + tokenId + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.REDEEM_CONSUME);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);

				break;
			case QueriesCodes.REDEEM_CHECK:
				String redeemCodeCheck = intent.getStringExtra(Keys._redeemCode);
				url = "Shared/CheckRedeem(" + redeemCodeCheck + "," + tokenId + ")";
				response = connector.sendGETRequest(url);
				Log.e("REDEEM_CHECK", response);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.REDEEM_CHECK);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				break;

			case QueriesCodes.ACCOUNT_UPLOAD_BY_ID:
				String account_upload_id = intent.getStringExtra(Keys._account_upload_id);

				String token1 = prefs.getString(Keys._tokenId, null);
				url = "AccountUpload/ByID(" + account_upload_id + "," + token1 + ")";
				response = connector.sendGETRequest(url);
				jsonParser.parseUploadSingleJSON(new JSONObject(response), account_upload_id);
				// Log.i("AccountUpload/ByID", response);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.ACCOUNT_UPLOAD_BY_ID);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.WARRANTY_BY_ACCOUNT_ID:
				// warranty list parse
				final int stepIteration = 20;
				int initialPosition = 0;
				int maxCount = stepIteration + 1;
				ArrayList<String> remains = new ArrayList<String>();
				do {
					url = "Warranty/ByAccountID(" + accountId + "," + tokenId + "," + initialPosition + "," + stepIteration + ",null)";
					response = connector.sendGETRequest(url);
					// Log.v("responce", response);
					JSONObject obj = new JSONObject(response);
					maxCount = obj.getInt("Total");
					remains = jsonParser.parseWarrantyJSON(new JSONObject(response), remains);
					initialPosition += stepIteration;
					resultData.putInt(Keys.actionIdentificator, QueriesCodes.WARRANTY_BY_ACCOUNT_ID);
					receiver.send(STATUS_FINISHED, resultData);

				} while (initialPosition <= maxCount);
				jsonParser.removeWarrantyRemains(remains);

				resultData.putInt(Keys.actionIdentificator, QueriesCodes.WARRANTY_BY_ACCOUNT_ID);
				receiver.send(STATUS_FINISHED, resultData);

				break;
			case QueriesCodes.ACCOUNT_BY_ID:
				if (intent.getStringExtra(Keys._accountId) != null) {
					accountId = intent.getStringExtra(Keys._accountId);
				}
				url = "Account/ByID(" + accountId + "," + tokenId + ")";
				response = connector.sendGETRequest(url);
				// Log.v("responce", response);
				UserInfo userInfo = jsonParser.parseUserInfoJSON(new JSONObject(response));
				resultData.putParcelable(Keys.userInfo, userInfo);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.ACCOUNT_SAVE:
				url = "Account/Save";
				response = connector.sendPostRequest(url, intent.getStringExtra(Keys.userInfoJson));
				// Log.v("responce", response);
				boolean isAccountSave = jsonParser.parseSuccessResponse(new JSONObject(response));
				resultData.putBoolean(Keys.isUserInfoSaved, isAccountSave);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.WARRANTY_SAVE:
				url = "Warranty/Save";
				JSONObject j = new JSONObject();
				j.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				j.put(Keys._warrantyId, intent.getStringExtra(Keys._warrantyId));
				// j.put("IsHidden", false);
				j.put("TransferTargetEmail", intent.getStringExtra(Keys._transferTargetEmail));
				j.put("TransferTargetEmailSet", true);
				response = connector.sendPostRequest(url, j.toString());
				Log.e("responce", response);
				TransferObject transfer = jsonParser.parseTransferResponse(new JSONObject(response));
				resultData.putInt(Keys.actionIdentificator, 0);
				resultData.putParcelable(Keys.isTransfer, transfer);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.ACCOUNT_UPLOAD_TRANSFER:
				url = "AccountUpload/Save";
				JSONObject jsonObjectTransferAccount = new JSONObject();
				jsonObjectTransferAccount.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObjectTransferAccount.put(Keys._accountId, prefs.getString(Keys._accountId, null));
				jsonObjectTransferAccount.put(Keys._account_upload_id, intent.getStringExtra(Keys._account_upload_id));
				jsonObjectTransferAccount.put("TransferTargetEmail", intent.getStringExtra(Keys._transferTargetEmail));
				jsonObjectTransferAccount.put("TransferTargetEmailSet", true);
				response = connector.sendPostRequest(url, jsonObjectTransferAccount.toString());
				Log.e("responce", response);
				TransferObject transferUpl = jsonParser.parseTransferResponse(new JSONObject(response));
				resultData.putParcelable(Keys.isTransfer, transferUpl);
				resultData.putInt(Keys.actionIdentificator, 0);
				resultData.putParcelable(Keys.isTransfer, transferUpl);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.WARRANTY_UPLOAD:
				url = "AccountUpload/Save";
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObject.put(Keys._accountId, prefs.getString(Keys._accountId, null));
				if (!checkValue(intent.getStringExtra(Keys._purchaseDate))) {
					jsonObject.put(Keys._purchaseDate, intent.getStringExtra(Keys._purchaseDate));
				}
				if (!checkValue(intent.getStringExtra(Keys._expirationDate))) {
					jsonObject.put(Keys._expirationDate, intent.getStringExtra(Keys._expirationDate));
				}
				if (intent.getExtras().containsKey(Keys._account_upload_id))
					jsonObject.put(Keys._account_upload_id, intent.getStringExtra(Keys._account_upload_id));
				if (!checkValue(intent.getStringExtra(Keys._productName)))
					jsonObject.put(Keys._productName, intent.getStringExtra(Keys._productName));
				if (!checkValue(intent.getStringExtra(Keys._storeName)))
					jsonObject.put(Keys._storeName, intent.getStringExtra(Keys._storeName));
				if (!checkValue(intent.getStringExtra(Keys._comments)))
					jsonObject.put(Keys._comments, intent.getStringExtra(Keys._comments));

				String base64 = null;
				Bitmap imageBitmap = null;
				// if (intent.hasExtra(Keys._base64File_Photo)) {
				// imageBitmap =
				// scaleBitmap(BitmapFactory.decodeFile(intent.getStringExtra(Keys._base64File_Photo)));
				// } else
				if (intent.hasExtra(Keys._base64File_Gallery)) {

					InputStream imageStream = null;
					String uri = intent.getStringExtra(Keys._base64File_Gallery);
					Uri u = Uri.parse(uri);
					// int scale = getScale(u);
					try {
						imageStream = getContentResolver().openInputStream(u);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}

					imageBitmap = BitmapFactory.decodeStream(imageStream, null, getBitmapOptions());

					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					imageBitmap.compress(Bitmap.CompressFormat.JPEG, 85, baos);
					byte[] b = baos.toByteArray();
					base64 = Base64.encode(b);

					baos.close();
					imageBitmap.recycle();

					if (null != imageStream)
						imageStream.close();

					jsonObject.put(Keys._base64File, base64);

					jsonObject.put("ContentType", "image/jpeg");
					jsonObject.put("ContentTypeSet", true);
				}
				response = connector.uploadImage(url, jsonObject.toString());
				boolean isUploadSuccess = jsonParser.parseSuccessResponse(new JSONObject(response));
				resultData.putBoolean(Keys._isUploadWarranty, isUploadSuccess);
				receiver.send(STATUS_FINISHED, resultData);

				break;
			case QueriesCodes.NEWS_RSS:
				newsParser.processInternal(getContentResolver());
				if (receiver != null)
					receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.INBOX:
				url = "Shared/AccountInbox";
				jsonObject = new JSONObject();
				jsonObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObject.put("LastSyncDate", DateUtis.decodeDateInbox(Calendar.getInstance().getTimeInMillis()));
				// jsonObject.put("LastSyncDate", null);
				response = connector.sendPostRequest(url, jsonObject.toString());
				Log.e("Shared/AccountInbox", response);
				jsonParser.parseInboxJSON(new JSONObject(response));
				if (null != receiver)
					receiver.send(STATUS_FINISHED, resultData);
				break;

			case QueriesCodes.RSS_NOTIFICATION:
				url = "Shared/AccountInbox";
				jsonObject = new JSONObject();
				jsonObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObject.put("LastSyncDate", DateUtis.decodeDate(Calendar.getInstance().getTimeInMillis()));
				// //Log.v("Shared/AccountInbox", jsonObject.toString());
				response = connector.sendPostRequest(url, jsonObject.toString());
				// Log.v("Shared/AccountInbox", response);
				ArrayList<RssNewsNotifyObject> newRssNews = jsonParser.parseRssNotificationJSON(new JSONObject(response));
				resultData.putParcelableArrayList(Keys.rssNewsNotif, newRssNews);
				receiver.send(STATUS_FINISHED, resultData);
				break;

			case QueriesCodes.FREE_CREDITS:
				url = "Shared/GetFree" + "(" + prefs.getString(Keys._tokenId, null) + ")";

				response = connector.sendGETRequest(url);
				jsonParser.parseGetFreeJSON(new JSONObject(response));
				receiver.send(STATUS_FINISHED, resultData);
				// //Log.v("Shared/GetFree", response);
				break;
			case QueriesCodes.BALANCE:
				url = "Shared/AccountBalance" + "(" + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				BalanceObject balanceObject = jsonParser.parseBalanceJSON(new JSONObject(response));
				resultData.putParcelable(Keys.balance, balanceObject);
				receiver.send(STATUS_FINISHED, resultData);
				// Log.e("Shared/AccountBalance", response);
				break;
			case QueriesCodes.RETAIL_STORE:
				// receiver.send(STATUS_RUNNING, null);
				url = "RetailStore/ByID" + "(" + intent.getStringExtra(Keys._retailStoreId) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				Log.e("resp", response);
				jsonParser.parseRetailsStoresJSON(new JSONObject(response));
				resultData.putString(Keys._retailStoreId, null);
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/AccountBalance", response);
				break;
			case QueriesCodes.SUBMIT_PURCHASE:
				url = "Android/SubmitPurchase";
				jsonObject = new JSONObject();
				jsonObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObject.put(Keys.requestId, intent.getIntExtra(Keys.requestId, 0));
				jsonObject.put(Keys.InAppProductID, intent.getStringExtra(Keys.InAppProductID));
				// Log.v("Android/SubmitPurchase", jsonObject.toString());
				response = connector.sendPostRequest(url, jsonObject.toString());
				resultData.putBoolean(Keys.isPurchaced, jsonParser.parseSuccessResponse(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case QueriesCodes.INBOX_INNER_WARRANTY_CHECK:
				url = "Shared/CheckWarrantyTransactionRedeem" + "(" + intent.getStringExtra(Keys._warrantyTransactionID) + ","
						+ prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_WARRANTY_CHECK);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/CheckWarrantyTransactionRedeem", response);//
				break;
			case QueriesCodes.INBOX_INNER_WARRANTY_COMSUME:
				url = "Shared/ConsumeWarrantyTransactionRedeem" + "(" + intent.getStringExtra(Keys._warrantyTransactionID) + ","
						+ prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_WARRANTY_COMSUME);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/ConsumeWarrantyTransactionRedeem", response);//
				break;
			case QueriesCodes.INBOX_INNER_WARRANTY_DISCARD:
				url = "Shared/DiscardWarrantyTransaction" + "(" + intent.getStringExtra(Keys._warrantyTransactionID) + ","
						+ prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_WARRANTY_DISCARD);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemLiteJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/DiscardWarrantyTransaction", response);
				break;
			case QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_CHECK:
				url = "Shared/CheckWarrantyRedeem" + "(" + intent.getStringExtra(Keys._warrantyId) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_CHECK);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/CheckWarrantyRedeem", response);
				break;
			case QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_COMSUME:
				url = "Shared/ConsumeWarrantyRedeem" + "(" + intent.getStringExtra(Keys._warrantyId) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_COMSUME);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/ConsumeWarrantyRedeem", response);
				break;
			case QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_DISCARD:
				url = "Shared/DiscardWarrantyTransaction" + "(" + intent.getStringExtra(Keys._warrantyId) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_TRANSFER_WARRANTY_DISCARD);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemLiteJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/DiscardWarrantyTransaction", response);
				break;
			case QueriesCodes.INBOX_INNER_WARRANTY_CLAIM:
				url = "Shared/ClaimAccountUpload" + "(" + intent.getStringExtra(Keys._account_upload_id) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_WARRANTY_CLAIM);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemLiteClaimJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/ClaimAccountUpload", response);
				break;
			case QueriesCodes.INBOX_INNER_WARRANTY_REJECT:
				url = "Shared/RejectAccountUpload" + "(" + intent.getStringExtra(Keys._account_upload_id) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.INBOX_INNER_WARRANTY_REJECT);
				resultData.putParcelable(Keys._redeemCode, jsonParser.parseRedeemLiteJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.v("Shared/RejectAccountUpload", response);
				break;

			case QueriesCodes.ACCOUNT_IDENTITY_BY_ACCOUNT_ID:
				url = "AccountIdentity/ByAccountID" + "(" + accountId + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putParcelableArray(Keys._accountIdentify, jsonParser.parseAccount_IedntifyJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.e("AccountIdentity/ByAccountID", response);
				break;
			case QueriesCodes.ADD_ACCOUNT_IDENTITY:
				url = "AccountIdentity/Save";
				jsonObject = new JSONObject();
				jsonObject.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));
				jsonObject.put(Keys._accountId, prefs.getString(Keys._accountId, null));
				jsonObject.put("AccountIdentityTypeID", intent.getStringExtra(Keys._account_identity_type));
				jsonObject.put("Value", intent.getStringExtra(Keys._email));
				if (intent.hasExtra(Keys._account_identity_by_id) && intent.getStringExtra(Keys._account_identity_by_id) != null) {
					jsonObject.put("AccountIdentityID", intent.getStringExtra(Keys._account_identity_by_id));
				}
				// Log.v("AccountIdentitySave", jsonObject.toString());
				response = connector.sendPostRequest(url, jsonObject.toString());
				resultData.putParcelable(Keys._accountIdentify_save, jsonParser.parseAccount_IedntifySaveJSON(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				// Log.e("AccountIdentitySave", response);

				break;
			case QueriesCodes.ACCOUNT_IDENTITY_DELETE_BY_ID:
				url = "AccountIdentity/DeleteByID(" + intent.getStringExtra(Keys._account_identity_by_id) + "," + prefs.getString(Keys._tokenId, null) + ")";
				response = connector.sendGETRequest(url);
				resultData.putParcelable(Keys._accountIdentify_delete, null);
				receiver.send(STATUS_FINISHED, resultData);
				// Log.e("AccountIdentity/DeleteByID", response);
				break;
			case QueriesCodes.PURCHASE:
				url = "Android/ProductList";
				response = connector.sendGETRequest(url);
				ArrayList<PurchaseObject> list = jsonParser.parsePurchaseJSON(new JSONObject(response));
				resultData.putParcelableArrayList(Keys._purchase, list);
				receiver.send(STATUS_FINISHED, resultData);
//				Log.e("Android/ProductList", response);
				break;
			default:
				break;
			}
		} catch (URISyntaxException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "Unable to connect server...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (ClientProtocolException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (IOException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			final Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		}

	}

	private boolean checkValue(String obj) {
		return (obj == null /* || TextUtils.isEmpty(obj) */);
	}

	private BitmapFactory.Options getBitmapOptions() {
		BitmapFactory.Options _bitmapOptions = new BitmapFactory.Options();
		_bitmapOptions.inTempStorage = new byte[256];
		_bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
		_bitmapOptions.inJustDecodeBounds = false; // this will request the bm
		_bitmapOptions.inSampleSize = 2; // scaled down by 4

		return _bitmapOptions;
	}

	public Bitmap scaleBitmap(Bitmap bitmap) {
		int newWidth = 6 * 240;
		int newHeight = 6 * 160;
		int origWidth = bitmap.getWidth();
		int origHeight = bitmap.getHeight();

		// If no new width or height were specified return the original bitmap
		if (newWidth <= 0 && newHeight <= 0) {
			return bitmap;
		}
		// Only the width was specified
		else if (newWidth > 0 && newHeight <= 0) {
			newHeight = (newWidth * origHeight) / origWidth;
		}
		// only the height was specified
		else if (newWidth <= 0 && newHeight > 0) {
			newWidth = (newHeight * origWidth) / origHeight;
		}
		// If the user specified both a positive width and height
		// (potentially different aspect ratio) then the width or height is
		// scaled so that the image fits while maintaining aspect ratio.
		// Alternatively, the specified width and height could have been
		// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
		// would result in whitespace in the new image.
		else {
			double newRatio = newWidth / (double) newHeight;
			double origRatio = origWidth / (double) origHeight;

			if (origRatio > newRatio) {
				newHeight = (newWidth * origHeight) / origWidth;
			} else if (origRatio < newRatio) {
				newWidth = (newHeight * origWidth) / origHeight;
			}
		}

		return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
	}
}
